<template>
  <div class="app-container">
    <el-card class="filter-container" :style="{ marginBottom: '20px' }" :shadow="defaultData.cardShadow">
      <div class="operate-container">
        <div>
          <i class="el-icon-search"></i>
          <span>筛选搜索</span>
        </div>
        <div>
          <el-button style="float: right" type="primary" @click="getList()">
            搜索
          </el-button>
          <el-button style="float: right; margin-right: 15px" @click="handleResetSearch()">
            重置
          </el-button>
        </div>
      </div>
      <div style="margin-top: 15px">
        <el-form :inline="true" :model="powerfulTableData.listQuery">
          <div class="screenForm">
            <el-form-item label="合作方" prop="partnerUuid" clearable style="width: 250px">
              <el-select v-model="powerfulTableData.listQuery.partnerUuid" placeholder="请选择合作方" style="width: 100%;">
                <el-option :label="item.partnerName" :value="item.partnerUuid" v-for="item in partnerList"
                  :key="item.partnerUuid" />
              </el-select>
            </el-form-item>
            <el-form-item label="收款单月份" prop="settlementMonth">
              <el-date-picker v-model="powerfulTableData.listQuery.settlementMonth" value-format="YYYYMM"
                format="YYYY-MM" type="month" placeholder="请选择收款单月份" style="width: 250px" />
            </el-form-item>
            <el-form-item label="结算状态" prop="settlementStatus" clearable style="width: 250px">
              <el-select v-model="powerfulTableData.listQuery.settlementStatus" placeholder="请选择结算状态"
                style="width: 100%;">
                <el-option :label="settlementStatusMap.get(v)" :value="v" v-for="v in settlementStatusMap.keys()"
                  :key="v" />
              </el-select>
            </el-form-item>
          </div>
        </el-form>

      </div>
    </el-card>

    <el-card :shadow="defaultData.cardShadow">
      <div class="operate-container">
        <div>
          <i class="el-icon-tickets"></i>
          <span>数据列表</span>
        </div>

        <div class="flex">
          <el-button type="success" class="btn-add" @click="handleAdd()">
            生成收款单
          </el-button>
        </div>
      </div>

      <div>
        <PowerfulTable :list="powerfulTableData.list" :header="header" :isSelect="false" :property="property"
          :pagination-property="{
            total: powerfulTableData.total,
            pageSizes: [2, 5, 7],
          }" @size-change="getList" @component-event="handleComponentChange" @btn-click="handleBtnClick">
          <template #createTime="{ row }">
            <div>{{ formatTime(row.createTime) }}</div>
          </template>
          <template #updateTime="{ row }">
            <div>{{ formatTime(row.updateTime) }}</div>
          </template>
          <template #settlementPeriod="{ row }">
            <div>{{ formatTime(row.settlementPeriodStart) }} 至 {{ formatTime(row.settlementPeriodEnd) }}</div>
          </template>
          <template #settlementStatus="{ row }">
            <el-tag :type="settlementStatusColorMap.get(row.settlementStatus) as any">
              {{ settlementStatusMap.get(row.settlementStatus) }}
            </el-tag>
          </template>
          <template #operation="{ row }">
            <el-dropdown>
              <el-button size="small">
                更多操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-item>
                  <el-button type="success" plain size="small"
                    @click="handleBtnClick({ params: 'detailList', row } as any)">
                    收款单明细
                  </el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button type="primary" plain size="small"
                    @click="handleBtnClick({ params: 'detail', row } as any)">
                    详情
                  </el-button>
                </el-dropdown-item>
                <el-dropdown-menu>
                  <el-dropdown-item>
                    <el-button type="primary" size="small" @click="handleBtnClick({ params: 'confirm', row } as any)">
                      确认
                    </el-button>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button type="danger" plain size="small"
                      @click="handleBtnClick({ params: 'payment', row } as any)">
                      收款
                    </el-button>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button type="warning" size="small" @click="handleBtnClick({ params: 'invoice', row } as any)">
                      开票
                    </el-button>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button type="success" size="small" @click="handleBtnClick({ params: 'edit', row } as any)">
                      编辑
                    </el-button>
                  </el-dropdown-item>
                </el-dropdown-menu>
                <el-dropdown-item>
                  <el-button type="danger" size="small" @click="handleBtnClick({ params: 'remove', row } as any)">
                    作废
                  </el-button>
                </el-dropdown-item>
              </template>
            </el-dropdown>
          </template>
        </PowerfulTable>
        <el-pagination v-model:current-page="powerfulTableData.listQuery.pageNum" class="pagination-container"
          v-model:page-size="powerfulTableData.listQuery.pageSize" :page-sizes="[10, 20, 30, 40]"
          layout="total, sizes, prev, pager, next" :total="powerfulTableData.total" @size-change="sizeChange"
          @current-change="getList" />
      </div>
    </el-card>

    <!-- 编辑区 -->
    <Update v-model:dialog="isDialog" v-if="isDialog" v-model:currentForm="currentForm" @refresh="getList" />
    <ConfirmDialog v-model:dialog="confirmDialog" v-if="confirmDialog" v-model:currentForm="confirmModel"
      @refresh="getList" />
    <InvoiceDialog v-model:dialog="invoiceDialog" v-if="invoiceDialog" v-model:currentForm="invoiceModel"
      @refresh="getList" />
    <PaymentDialog v-model:dialog="paymentDialog" v-if="paymentDialog" v-model:currentForm="paymentModel"
      @refresh="getList" />
    <DetailDialog v-model:dialog="detailDialog" v-if="detailDialog" v-model:Id="rowId" @refresh="getList" />
    <DetailListDialog v-model:dialog="detailListDialog" v-if="detailListDialog" v-model:Id="rowId" @refresh="getList" />
  </div>
</template>
<script lang="ts" setup>
import { querySettlementPage, invalidSettlement } from '@/api/settlement'
import { useData, Model } from './indexData'
import { Handlers } from 'el-plus-powerful-table'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores'
import Update from './update.vue'
import ConfirmDialog from './confirmDialog.vue'
import InvoiceDialog from './invoiceDialog.vue'
import PaymentDialog from './paymentDialog.vue'
import DetailDialog from './detailDialog.vue'
import DetailListDialog from './detailListDialog.vue'
import { partnerQuery } from "@/api/user"
import { formatTime } from '@/utils'
import { settlementStatusColorMap, property, settlementStatusMap } from '@/config/constants'
const { header, powerfulTableData, currentForm, isDialog } = useData()

// 导入对话框显示状态
import { defaultData as defaultForm } from './indexData'
const userStore = useUserStore()

const partnerList = ref<any>([])
const confirmDialog = ref<boolean>(false)
const invoiceDialog = ref<boolean>(false)
const paymentDialog = ref<boolean>(false)
const detailDialog = ref<boolean>(false)
const detailListDialog = ref<boolean>(false)

const rowId = ref<string>('')

const confirmModel = reactive({
  confirmUserName: '',
  partnerConfirmUser: '',
  partnerConfirmTime: '',
  settlementUuid: '',
})

const paymentModel = reactive({
  receivedAmount: '', //收款金额
  receivedType: "", //收款类型
  settlementUuid: '',
})

const invoiceModel = reactive({
  invoiceType: 1,  //发票类型（1 增值税普票 2 增值税专票）
  invoiceTitle: "", //发票抬头
  invoiceTaxNumber: "", //发票税号
  invoiceAmount: '', //开票金额
  invoiceNumber: "", //发票号码
  invoiceTime: "", //开票时间
  settlementUuid: '',
})

onMounted(() => {
  partnerQuery({ pageNum: 1, pageSize: 1000 }).then((res: any) => {
    partnerList.value = res.data.list || []
  })
})

// 获取用户列表
const getList = () => {
  querySettlementPage(powerfulTableData.listQuery).then((res) => {
    console.log(res)
    powerfulTableData.list = res.data.list
    powerfulTableData.total = res.data.total
  })
}
// 分页大小改变
const sizeChange = (val: number) => {
  powerfulTableData.listQuery.pageSize = val
  getList()
}
getList()

const handleComponentChange: Handlers['component-event'] = (payload) => {
  switch (payload.componentName) {
    // 停用事件
    case 'switch':
      const e = payload.row
      if (userStore.userInfo.id == e.id && e.status === 0) {
        ElMessage.error('你的账号已被停用！')
      }
      break
  }
}

const handleAdd = () => {
  Object.assign(currentForm.value, defaultForm())
  isDialog.value = true;
}

const handleBtnClick: Handlers['btn-click'] = ({ params, row }) => {
  console.log(row)
  switch (params) {
    case 'edit':
      isDialog.value = true;
      Object.assign(currentForm.value, JSON.parse(JSON.stringify(row)))
      break
    case 'confirm':
      confirmDialog.value = true;
      confirmModel.settlementUuid = row.settlementUuid
      break
    case 'invoice':
      invoiceDialog.value = true;
      invoiceModel.settlementUuid = row.settlementUuid
      break
    case 'payment':
      paymentDialog.value = true;
      paymentModel.settlementUuid = row.settlementUuid
      break
    case 'detail':
      detailDialog.value = true;
      rowId.value = row.settlementUuid
      break
    case 'detailList':
      detailListDialog.value = true;
      rowId.value = row.settlementUuid
      break
    case 'remove':
      remove(row)
      break
  }
}

const remove = (row: Model) => {
  ElMessageBox.confirm('是否确认作废', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    invalidSettlement({ settlementUuid: row.settlementUuid }).then((res: any) => {
      if (res.code === 200) {
        ElMessage.success('作废成功')
        getList()
      }
    })
  })
}


// 重置
const handleResetSearch = () => {
  Object.keys(powerfulTableData.listQuery).forEach((item: any) => {
    let arr = ['pageNum', 'pageSize']
    if (arr.indexOf(item) == -1) {
      ; (powerfulTableData.listQuery as { [s: string]: string | number })[item] =
        ''
    }
  })
  getList()
}
</script>
